import React, { createContext, useContext, useEffect, useState } from 'react';
import { useAdminAuth } from './AdminAuthContext';

// 创建权限上下文
const AdminPermissionContext = createContext();

/**
 * 管理员权限提供者组件
 * 负责获取和管理当前管理员的权限信息
 */
export const AdminPermissionProvider = ({ children }) => {
  const { currentUser, isAuthenticated } = useAdminAuth();
  const [permissions, setPermissions] = useState([]);
  const [loading, setLoading] = useState(true);

  // 当用户信息变化时，获取权限信息
  useEffect(() => {
    const fetchPermissions = async () => {
      if (!isAuthenticated || !currentUser) {
        setPermissions([]);
        setLoading(false);
        return;
      }

      try {
        // 在实际项目中，这里应该调用真实的API接口获取权限信息
        // const response = await axios.get('/admin/permissions', {
        //   headers: { Authorization: `Bearer ${token}` }
        // });
        // setPermissions(response.data);

        // 模拟数据：根据用户角色返回不同的权限列表
        // 这里假设用户有一个role字段
        let userPermissions = [];
        
        if (currentUser.role === 'super_admin') {
          // 超级管理员拥有所有权限
          userPermissions = [
            'dashboard_view',
            'users_view', 'users_create', 'users_edit', 'users_delete',
            'face_analysis_config', 'palm_analysis_config', 'bazi_analysis_config',
            'dream_interpretation_config', 'tarot_card_config', 'numerology_config',
            'app_version_manage', 'system_settings', 'system_logs_view'
          ];
        } else if (currentUser.role === 'admin') {
          // 普通管理员拥有部分权限
          userPermissions = [
            'dashboard_view',
            'users_view', 'users_create', 'users_edit',
            'face_analysis_config', 'palm_analysis_config', 'bazi_analysis_config',
            'dream_interpretation_config', 'tarot_card_config', 'numerology_config'
          ];
        } else if (currentUser.role === 'content_manager') {
          // 内容管理员只拥有内容管理相关权限
          userPermissions = [
            'dashboard_view',
            'face_analysis_config', 'palm_analysis_config', 'bazi_analysis_config',
            'dream_interpretation_config', 'tarot_card_config', 'numerology_config'
          ];
        }
        
        setPermissions(userPermissions);
      } catch (error) {
        console.error('获取权限信息失败:', error);
        setPermissions([]);
      } finally {
        setLoading(false);
      }
    };

    fetchPermissions();
  }, [isAuthenticated, currentUser]);

  // 检查用户是否拥有指定权限
  const hasPermission = (permission) => {
    if (!isAuthenticated) return false;
    // 超级管理员拥有所有权限
    if (currentUser?.role === 'super_admin') return true;
    return permissions.includes(permission);
  };

  // 检查用户是否拥有指定角色
  const hasRole = (role) => {
    if (!isAuthenticated || !currentUser) return false;
    
    // 角色层级关系：super_admin > admin > content_manager
    if (currentUser.role === 'super_admin') return true;
    if (currentUser.role === 'admin' && role === 'content_manager') return true;
    return currentUser.role === role;
  };

  const value = {
    permissions,
    loading,
    hasPermission,
    hasRole,
  };

  return (
    <AdminPermissionContext.Provider value={value}>
      {children}
    </AdminPermissionContext.Provider>
  );
};

/**
 * 自定义Hook，用于在组件中获取和使用权限信息
 */
export const useAdminPermissions = () => {
  const context = useContext(AdminPermissionContext);
  if (!context) {
    throw new Error('useAdminPermissions must be used within an AdminPermissionProvider');
  }
  return context;
};